package com.ysd.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ysd.dao.modulesDao;
import com.ysd.entity.Modules;
import com.ysd.util.treeUtil;

@RestController
public class modulesController {
	@Autowired
	modulesDao md;
	//查询所有模块
	@RequestMapping("/getModules")
	public Object getModules() {
		List<Modules> mm = md.findAll();
		return mm;
	}	
	
	@GetMapping("/tree")
	public List<treeUtil> gettree2() {
		List<Modules> mlist=md.findAll();
		List<treeUtil> tlist=new ArrayList<treeUtil>();
		
		for (Modules mm : mlist) {
			int id=mm.getMid();
			Integer pid=mm.getMparentid();
			String title=mm.getMname();
			String href=mm.getMpath();
			Integer weight=mm.getMweight();
			if (mm.getMparentid()==null) {
				List<treeUtil> tlist1=new ArrayList<treeUtil>();
				List<Modules> children=findChildren(id);
				for (Modules c : children) {
					int id1=c.getMid();
					Integer pid1=c.getMparentid();
					String title1=c.getMname();
					String href1=c.getMpath();
					Integer weight1=c.getMweight();
					tlist1.add(new treeUtil(id1, pid1, title1,href1,weight1,null));
				}
				tlist.add(new treeUtil(id, pid, title,href,weight,tlist1));
			
			}
		}
		return tlist;
	}	
	
	private List<Modules> findChildren(int id) {
		// TODO Auto-generated method stub
		return md.getChildren(id);
	}

	@RequestMapping("/addModules")
	public Object addModules(Modules m) {
		if (md.saveAndFlush(m) != null) {
			return 1;
		} else {
			return 0;
		}
	}
	
	@RequestMapping("/deleteModules")
	public Integer delModules(Integer Id) {
		try {
			md.delete(Id);
			return 1;
		} catch (Exception e) {
			// TODO: handle exception
			return 0;
		}

	}
	
	@RequestMapping("/updateModules")
	public Object updateModules(Modules m) {
		if (md.saveAndFlush(m) != null) {
			return 1;
		} else {
			return 0;
		}
	}
}
